package com.wanyangproject.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mm.opensdk.utils.Log;
import com.wanyangproject.R;
import com.wanyangproject.base.MyApp;
import com.wanyangproject.entity.DuanXinDengLuEntity;
import com.wanyangproject.entity.DuanXinWeiZhuCeEntity;
import com.wanyangproject.entity.HuoQuYanZhengMaEntity;
import com.wanyangproject.entity.LoginEntity;
import com.wanyangproject.entity.WeiXinDengLuEntity;
import com.wanyangproject.entity.Weixin400Entity;
import com.wanyangproject.shouye.ZhengCeFaGuiActivity;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.SharedPreferencesPhone;
import com.wanyangproject.utils.SharedPreferencesToken;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

//     登录界面
public class LoginActivity extends AppCompatActivity {

    @BindView(R.id.mima_login)
    TextView mimaLogin;
    @BindView(R.id.duanxin_login)
    TextView duanxinLogin;
    @BindView(R.id.et_zhanghao)
    EditText etZhanghao;
    @BindView(R.id.et_mima)
    EditText etMima;
    @BindView(R.id.image_eye_close)
    ImageView imageEyeClose;
    @BindView(R.id.image_eye_open)
    ImageView imageEyeOpen;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.login_tv_register)
    TextView loginTvRegister;
    @BindView(R.id.login_tv_wangji_mima)
    TextView loginTvWangjiMima;
    @BindView(R.id.image_weixin)
    ImageView imageWeixin;
    @BindView(R.id.image_clean)
    ImageView imageClean;
    @BindView(R.id.relative_duanxin)
    RelativeLayout relativeDuanxin;
    @BindView(R.id.relative_mima)
    RelativeLayout relativeMima;
    @BindView(R.id.view_mima)
    View viewMima;
    @BindView(R.id.view_duanxin)
    View viewDuanxin;
    @BindView(R.id.et_yanzhengma)
    EditText etYanzhengma;
    @BindView(R.id.tv_huoqu_yanzhengma)
    TextView tvHuoquYanzhengma;
    @BindView(R.id.view_shu)
    View viewShu;
    private Boolean isOK = false;
    private String response;
    private int num;
    private HuoQuYanZhengMaEntity huoQuYanZhengMaEntity;
    private LoginEntity loginEntity;
    //    微信的APP ID
    private static final String APP_ID_WEChat = "wx363ae6178db5e958";
    //    IWXAPI是第三方app和微信通信的openapi接口
    public static IWXAPI iwxapi;
    private NetWork netWork;
    private String wxopenid;
    private int denglu = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 21) {
            View dview = getWindow().getDecorView();
            dview.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }


        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("wx");
        netWork = new NetWork();
        registerReceiver(netWork, intentFilter);


        if (etZhanghao.getText().toString().equals("")) {
            imageClean.setVisibility(View.GONE);
        }


        if (etYanzhengma.getText().toString().equals("")) {
            imageEyeClose.setVisibility(View.GONE);
        }


        etZhanghao.addTextChangedListener(new TextWatcher() {
            @Override  //   输入文字之前的状态
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override // 输入文字中的状态
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override  // 输入文字之后的状态
            public void afterTextChanged(Editable editable) {
                imageClean.setVisibility(View.VISIBLE);
                if(etZhanghao.getText().toString().trim().equals("") || etMima.getText().toString().trim().equals("")){
                    btnLogin.setBackgroundResource(R.drawable.login_weitianxie);
                }else{
                    btnLogin.setBackgroundResource(R.drawable.login_tianxie);
                }
            }
        });


        etMima.addTextChangedListener(new TextWatcher() {
            @Override  //   输入文字之前的状态
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override // 输入文字中的状态
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override  // 输入文字之后的状态
            public void afterTextChanged(Editable editable) {
                imageEyeOpen.setVisibility(View.VISIBLE);
                if(etZhanghao.getText().toString().trim().equals("") || etMima.getText().toString().trim().equals("")){
                    btnLogin.setBackgroundResource(R.drawable.login_weitianxie);
                }else{
                    btnLogin.setBackgroundResource(R.drawable.login_tianxie);
                }
            }
        });








        etYanzhengma.addTextChangedListener(new TextWatcher() {
            @Override  //   输入文字之前的状态
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override // 输入文字中的状态
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override  // 输入文字之后的状态
            public void afterTextChanged(Editable editable) {
                if(etZhanghao.getText().toString().trim().equals("") || etYanzhengma.getText().toString().trim().equals("")){
                    btnLogin.setBackgroundResource(R.drawable.login_weitianxie);
                }else{
                    btnLogin.setBackgroundResource(R.drawable.login_tianxie);
                }
            }
        });

//
//
//        //        微信
        regToWx();

    }


    class NetWork extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            wxopenid = intent.getStringExtra("wxopenid");
//            Toast.makeText(context, wxopenid + wxnickname + wxheadimgurl, Toast.LENGTH_SHORT).show();
            System.out.println(wxopenid + "        微信openID");
//            微信登录
            initWeChatHttp();
        }
    }


    //    **//禁止使用返回键返回到上一页,但是可以直接退出程序**
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;//不执行父类点击事件
        }
        return super.onKeyDown(keyCode, event);//继续执行父类其他点击事件
    }






    //    微信登录
    private void initWeChatHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "user/login")
                .addParams("wxkey", wxopenid)
                .addParams("uuid", "123")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println(e + "               微信eeee");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response + "       微信登录的网络请求");
                        ContractUtils.Code500(LoginActivity.this,response);
                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            WeiXinDengLuEntity weiXinDengLuEntity = gson.fromJson(response, WeiXinDengLuEntity.class);
                            ContractUtils.setTOKEN(weiXinDengLuEntity.getResponse().getToken());
                            ContractUtils.setParkId(weiXinDengLuEntity.getResponse().getParkInfo().getParkId());
                            ContractUtils.setPhone(weiXinDengLuEntity.getResponse().getUsername());
                            ContractUtils.setYuanquname(weiXinDengLuEntity.getResponse().getParkInfo().getParkName());
//                            ContractUtils.setTypeId(weiXinDengLuEntity.getResponse().getTypeId());
//                            ContractUtils.setTypeId22(weiXinDengLuEntity.getResponse().getTypeId2());
                            Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                            startActivity(intent);
                            finish();
                        } else if (response.indexOf("400") != -1) {
                            Gson gson1 = new Gson();
                            Weixin400Entity weixin400Entity = gson1.fromJson(response, Weixin400Entity.class);
                            Toast.makeText(LoginActivity.this, weixin400Entity.getMsg(), Toast.LENGTH_SHORT).show();
                            if (weixin400Entity.getResponse().getBindPhone().equals("1")) {
                                Intent intent = new Intent(LoginActivity.this, BangDingShouJiHaoActivity.class);
                                intent.putExtra("wxopenid", wxopenid);
                                System.out.println(wxopenid + "     chuan微信openid");
                                startActivity(intent);
                            }
                        }
                    }
                });
    }

    private void regToWx() {
//        通过WXAPOFactory工厂，获取IWXAPI的实例
        iwxapi = WXAPIFactory.createWXAPI(this, APP_ID_WEChat, true);
//        将应用的APP ID注册到微信
        iwxapi.registerApp(APP_ID_WEChat);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWork);
    }


    @OnClick({R.id.et_yanzhengma, R.id.tv_huoqu_yanzhengma, R.id.view_mima, R.id.view_duanxin, R.id.relative_mima, R.id.relative_duanxin, R.id.image_clean, R.id.mima_login, R.id.duanxin_login, R.id.et_zhanghao, R.id.et_mima, R.id.image_eye_close, R.id.image_eye_open, R.id.btn_login, R.id.login_tv_register, R.id.login_tv_wangji_mima, R.id.image_weixin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
//            清除账号
            case R.id.image_clean:
                etZhanghao.setText("");
                break;
//            密码登录
            case R.id.mima_login:
                denglu = 0;
                viewMima.setVisibility(View.VISIBLE);
                viewDuanxin.setVisibility(View.GONE);
                mimaLogin.setTextColor(getResources().getColor(R.color.white));
                duanxinLogin.setTextColor(Color.parseColor("#cccccc"));
                relativeMima.setVisibility(View.VISIBLE);
                relativeDuanxin.setVisibility(View.GONE);
                break;
//            短信登录
            case R.id.duanxin_login:
                denglu = 1;
                viewMima.setVisibility(View.GONE);
                viewDuanxin.setVisibility(View.VISIBLE);
                relativeMima.setVisibility(View.GONE);
                relativeDuanxin.setVisibility(View.VISIBLE);
                viewShu.setVisibility(View.VISIBLE);
                mimaLogin.setTextColor(Color.parseColor("#cccccc"));
                duanxinLogin.setTextColor(getResources().getColor(R.color.white));
                break;
//            输入账号
            case R.id.et_zhanghao:
                break;
//            输入密码
            case R.id.et_mima:
                break;
//            关闭密码
            case R.id.image_eye_close:

                break;
////            打开密码
            case R.id.image_eye_open:
                if (isOK) {
//                    如果选中显示密码
//                    imageEyeOpen.setImageResource(R.mipmap.close_eye);
                    imageEyeOpen.setImageResource(R.drawable.close_eyewhite);


//                    imageEyeClose.setImageResource(R.mipmap.open_eye);
                    etMima.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    isOK = false;
                } else {
//                    否则隐藏密码
//                    imageEyeOpen.setImageResource(R.mipmap.open_eye);
                    imageEyeOpen.setImageResource(R.mipmap.open_eye_white);


//                    imageEyeClose.setImageResource(R.mipmap.close_eye);
                    etMima.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    isOK = true;
                }
                break;
//            登录按钮
            case R.id.btn_login:
                if (denglu == 0) {
                    if (TextUtils.isEmpty(etZhanghao.getText().toString().trim()) && TextUtils.isEmpty(etMima.getText().toString().trim())) {
                        Toast.makeText(this, "手机号和密码不能为空", Toast.LENGTH_SHORT).show();
                    } else if (TextUtils.isEmpty(etZhanghao.getText().toString().trim())) {
                        Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                    } else if (TextUtils.isEmpty(etMima.getText().toString().trim())) {
                        Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
                    } else if (etZhanghao.length() < 11) {
                        Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                    } else {
//                    登录的网络请求
                        initLoginHttp();
                    }
                } else if (denglu == 1) {
                    if (TextUtils.isEmpty(etZhanghao.getText().toString().trim())) {
                        Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                    } else if (TextUtils.isEmpty(etYanzhengma.getText().toString().trim())) {
                        Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
                    } else {
                        //                    登录的网络请求
                        initLoginHttp();
                    }
                }

//                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
//                startActivity(intent);
                break;
//            注册新用户
            case R.id.login_tv_register:
                Intent intent1 = new Intent(this, RegisterActivity.class);
                startActivity(intent1);
                break;
//            忘记密码
            case R.id.login_tv_wangji_mima:
                Intent intent2 = new Intent(LoginActivity.this, WangJiMiMaActivity.class);
                startActivity(intent2);
                break;
//            微信图标登陆
            case R.id.image_weixin:
                if (!LoginActivity.iwxapi.isWXAppInstalled()) {
                    Toast.makeText(this, "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
                    return;
                }

                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_sdk_demo_test";
                iwxapi.sendReq(req);
                System.out.println("0000000000");

                break;
            case R.id.view_mima:
                break;
            case R.id.view_duanxin:
                break;
//            短信登录  输入验证码
            case R.id.et_yanzhengma:
                break;
//            短信登录获取验证码
            case R.id.tv_huoqu_yanzhengma:

                if (ContractUtils.isChinaPhoneLegal(etZhanghao.getText().toString().trim()) == false) {
                    Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (etZhanghao.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请先输入手机号", Toast.LENGTH_SHORT).show();
                } else {

                    //                获取验证码的网络请求
                    initHuoQuYanZhengMaHttp();
                }
                break;
        }
    }

















    //   短信登录     获取验证码网络请求
    private void initHuoQuYanZhengMaHttp() {
//        final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this);
//        progressDialog.setTitle("提示");
//        progressDialog.setMessage("请等待...");
//        progressDialog.setCancelable(false);
//        progressDialog.show();
        OkHttpUtils.post()
//                .url(ContractUtils.LOGIN_URL + "index/sendsms")
                .url(ContractUtils.LOGIN_URL + "index/sendsmswei")
                .addParams("phone", etZhanghao.getText().toString().trim())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
//                        progressDialog.dismiss();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response + "     获取验证码的网络请求");

                        if (response.indexOf("200") != -1) {
                            new Thread() {
                                @Override
                                public void run() {
                                    super.run();
                                    try {
                                        num = 60;
                                        while (num > 0) {
//                                       不可点击
                                            tvHuoquYanzhengma.setClickable(false);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
//                                        tvHuoquYanzhengma.setBackgroundResource(R.drawable.shape_huoqu_huise);
//                                        tvHuoquYanzhengma.setText("倒计时"+num+"s");
                                                    tvHuoquYanzhengma.setText(num + "s后重新获取");
                                                }
                                            });

                                            Thread.sleep(1000);
                                            num = num - 1;
                                        }

                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
//                                    tvHuoquYanzhengma.setBackgroundResource(R.drawable.shape_huoqu);
                                                tvHuoquYanzhengma.setClickable(true);
                                                tvHuoquYanzhengma.setText("重新获取");
                                            }
                                        });

                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }.start();
                            Gson gson = new Gson();
                            huoQuYanZhengMaEntity = gson.fromJson(response, HuoQuYanZhengMaEntity.class);
                            Toast.makeText(LoginActivity.this, huoQuYanZhengMaEntity.getMsg(), Toast.LENGTH_SHORT).show();
                        }else if(response.indexOf("400") != -1){
                            Gson gson = new Gson();
                            DuanXinWeiZhuCeEntity duanXinWeiZhuCeEntity = gson.fromJson(response, DuanXinWeiZhuCeEntity.class);
                            Toast.makeText(LoginActivity.this, duanXinWeiZhuCeEntity.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    //    账号密码登录    登录的网络请求
    private void initLoginHttp() {
        if (denglu == 0) { // 账号密码登录
            final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this);
            progressDialog.setTitle("提示");
            progressDialog.setMessage("请等待...");
            progressDialog.setCancelable(false);
            progressDialog.show();
            OkHttpUtils.post()
                    .url(ContractUtils.LOGIN_URL + "user/login")
                    .addParams("phone", etZhanghao.getText().toString().trim())
                    .addParams("password", etMima.getText().toString().trim())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            progressDialog.dismiss();
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            progressDialog.dismiss();
                            System.out.println(response + "       密码登录的网络请求");
                            ContractUtils.Code500(LoginActivity.this,response);
                            if (response.indexOf("200") != -1) {
                                Gson gson = new Gson();
                                loginEntity = gson.fromJson(response, LoginEntity.class);
                                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                                //                        记住登录状态
                                SharedPreferencesPhone.savePhone(MyApp.getContext(), response);
                                ContractUtils.setTOKEN(loginEntity.getResponse().getToken());
                                ContractUtils.setParkId(loginEntity.getResponse().getParkInfo().getParkId());
                                ContractUtils.setPhone(loginEntity.getResponse().getUsername());
                                ContractUtils.setYuanquname(loginEntity.getResponse().getParkInfo().getParkName());
                                ContractUtils.setTypeId(loginEntity.getResponse().getTypeId());
                                ContractUtils.setTypeId22(loginEntity.getResponse().getTypeId2());

////                            保存Token
//                                SharedPreferencesToken.saveToken(MyApp.getContext(),loginEntity.getResponse().getToken());
                                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                                intent.putExtra("parkname", loginEntity.getResponse().getParkInfo().getParkName());
                                startActivity(intent);
                                finish();
                            } else {
                                Toast.makeText(LoginActivity.this, "账号或密码不正确", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        } else if (denglu == 1) {

            if(huoQuYanZhengMaEntity == null){
                Toast.makeText(this, "请填写正确的验证码！", Toast.LENGTH_SHORT).show();
                return;
            }



            final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this);
            progressDialog.setTitle("提示");
            progressDialog.setMessage("请等待...");
            progressDialog.setCancelable(false);
            progressDialog.show();
            OkHttpUtils.post()
                    .url(ContractUtils.LOGIN_URL + "user/login")
                    .addParams("phone", etZhanghao.getText().toString().trim())
                    .addParams("code", etYanzhengma.getText().toString().trim())
                    .addParams("authId", huoQuYanZhengMaEntity.getResponse().getAuthId())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            System.out.println(e + "      短信eee");
                            progressDialog.dismiss();
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            progressDialog.dismiss();
                            System.out.println(response + "       短信登录的网络请求");
                            ContractUtils.Code500(LoginActivity.this,response);
                            if (response.indexOf("200") != -1) {
                                Gson gson = new Gson();
                                DuanXinDengLuEntity duanXinDengLuEntity = gson.fromJson(response, DuanXinDengLuEntity.class);
                                //                        记住登录状态
                                SharedPreferencesPhone.savePhone(MyApp.getContext(), response);
                                ContractUtils.setTOKEN(duanXinDengLuEntity.getResponse().getToken());
                                ContractUtils.setParkId(duanXinDengLuEntity.getResponse().getParkInfo().getParkId());
                                ContractUtils.setPhone(duanXinDengLuEntity.getResponse().getUsername());
//                            保存Token
                                SharedPreferencesToken.saveToken(MyApp.getContext(), duanXinDengLuEntity.getResponse().getToken());
                                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                                startActivity(intent);
                                finish();
                            } else {
                                Toast.makeText(LoginActivity.this, "请先注册", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }


    }
}
